﻿using LibGit2Sharp;
using LibGit2Sharp.Handlers;
using MengCC.Plugin.SDK;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security;
using System.Text;

namespace MengCC.Plugin.GitWithPassword
{
    public class GitPlugin
    {
        public bool Run(PluginContext pluginContext)
        {
			try
			{
                var options = JsonConvert.DeserializeObject<Options>(pluginContext.GetOptions());

                var userName = options.UserName;
                char[] pChar = options.Password.ToCharArray();

                SecureString password = new SecureString();
                foreach (var item in pChar)
                {
                    password.AppendChar(item);
                }
                CredentialsHandler credentialsProvider = (_url, _user, _cred) => new SecureUsernamePasswordCredentials()
                {
                    Username = userName,
                    Password = password
                };
               
                if (!Directory.Exists(pluginContext.Wordspace) || Directory.GetFiles(pluginContext.Wordspace).Length == 0)
                {
                    pluginContext.Write("仓库不存在，新载入");
                    Repository.Clone(options.RemoteUrl, pluginContext.Wordspace, new CloneOptions
                    {
                        CredentialsProvider = credentialsProvider,
                        OnProgress = msg =>
                        {
                            pluginContext.Write(msg);
                            return true;
                        },
                        BranchName=options.BranchName
                    });
                }
                else
                {
                    pluginContext.Write("仓库已存在，更新");
                    using (var repo = new Repository(pluginContext.Wordspace))
                    {
                        FetchOptions fetchoptions = new FetchOptions();
                        fetchoptions.CredentialsProvider = credentialsProvider;
                        fetchoptions.OnProgress = msg =>
                        {
                            pluginContext.Write(msg);
                            return true;
                        };
                        foreach (Remote remote in repo.Network.Remotes)
                        {
                            IEnumerable<string> refSpecs = remote.FetchRefSpecs.Select(x => x.Specification);
                            Commands.Pull(repo, new Signature(userName, userName, new DateTimeOffset(DateTime.Now)), new PullOptions { FetchOptions = fetchoptions });
                        }
                    }
                }
                return true;
            }
			catch (Exception ex)
			{
                pluginContext.Write(ex.ToString());
                return true;
            }

        }
    }
}
